// 云函数 - 微信支付回调处理
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  console.log('收到支付回调:', event)
  
  try {
    // 验证支付结果
    const { returnCode, resultCode, outTradeNo, totalFee, transactionId, attach } = event
    
    if (returnCode !== 'SUCCESS' || resultCode !== 'SUCCESS') {
      console.log('支付失败:', event)
      return {
        returnCode: 'SUCCESS',
        returnMsg: 'OK'
      }
    }

    // 解析attach参数获取订单信息
    let orderInfo = null
    if (attach) {
      try {
        orderInfo = JSON.parse(attach)
      } catch (e) {
        console.error('解析attach参数失败:', e)
      }
    }

    // 查找对应订单
    const orderResult = await db.collection('orders')
      .where({
        orderNo: outTradeNo
      })
      .get()

    if (orderResult.data.length === 0) {
      console.error('订单不存在:', outTradeNo)
      return {
        returnCode: 'SUCCESS',
        returnMsg: 'OK'
      }
    }

    const order = orderResult.data[0]
    
    // 检查订单状态，避免重复处理
    if (order.status !== 'pending_payment') {
      console.log('订单状态异常，跳过处理:', order.status)
      return {
        returnCode: 'SUCCESS',
        returnMsg: 'OK'
      }
    }

    // 验证订单号一致性（可选验证，主要依赖outTradeNo）
    if (orderInfo && orderInfo.o && orderInfo.o !== outTradeNo) {
      console.error('订单号不匹配:', { attachOrderNo: orderInfo.o, actualOrderNo: outTradeNo })
      return {
        returnCode: 'SUCCESS',
        returnMsg: 'OK'
      }
    }

    // 验证支付金额（支持组合支付）
    const wechatPayment = order.paymentMethods.find(method => method.id === 'wechat')
    const comboPayment = order.paymentMethods.find(method => method.id === 'combo')
    
    let expectedAmount = 0
    let paymentType = 'wechat'
    let balanceAmount = 0
    
    if (comboPayment && comboPayment.wechatAmount > 0) {
      // 组合支付
      expectedAmount = Math.round(comboPayment.wechatAmount * 100)
      paymentType = 'combo'
      balanceAmount = comboPayment.balanceAmount || 0
    } else if (wechatPayment && wechatPayment.amount > 0) {
      // 纯微信支付
      expectedAmount = Math.round(wechatPayment.amount * 100)
    }
    
    if (totalFee !== expectedAmount) {
      console.error('支付金额不匹配:', { totalFee, expectedAmount, paymentType })
      return {
        returnCode: 'SUCCESS',
        returnMsg: 'OK'
      }
    }

    // 处理组合支付的余额扣除（微信支付成功后才扣除余额）
    if (paymentType === 'combo' && balanceAmount > 0) {
      await db.collection('users').where({
        _openid: order.userId
      }).update({
        data: {
          balance: db.command.inc(-balanceAmount),
          updateTime: new Date()
        }
      })
    }

    // 更新订单状态为待发货
    await db.collection('orders').doc(order._id).update({
      data: {
        status: 'pending_shipment',
        payTime: new Date(),
        transactionId: transactionId,
        updateTime: new Date()
      }
    })

    // 减少商品库存并增加销量
    for (const item of order.items) {
      await db.collection('goods').doc(item.productId).update({
        data: {
          stock: db.command.inc(-item.quantity),
          sales: db.command.inc(item.quantity),
          updateTime: new Date()
        }
      })
    }

    // 更新用户总消费额
    const totalConsumptionAmount = order.actualAmount // 使用订单实际金额
    await db.collection('users').where({
      _openid: order.userId
    }).update({
      data: {
        totalConsumption: db.command.inc(totalConsumptionAmount),
        updateTime: new Date()
      }
    })

    console.log('支付回调处理成功:', outTradeNo)
    
    return {
      returnCode: 'SUCCESS',
      returnMsg: 'OK'
    }

  } catch (error) {
    console.error('支付回调处理失败:', error)
    return {
      returnCode: 'FAIL',
      returnMsg: error.message
    }
  }
}